package com.jrx.anytxn.customer.service.impl;

import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.*;
import com.jrx.anytxn.customer.bean.CustomerInfoBean;
import com.jrx.anytxn.customer.bean.CustomerInfoCreationBean;
import com.jrx.anytxn.customer.constant.CustomerConstant;
import com.jrx.anytxn.customer.dto.customer.CustomerSupplyReq;
import com.jrx.anytxn.customer.entity.CmCustomerAddressInfo;
import com.jrx.anytxn.customer.entity.CmCustomerContactInfo;
import com.jrx.anytxn.customer.entity.CmCustomerFirstLevel;
import com.jrx.anytxn.customer.entity.CmCustomerSecondLevel;
import com.jrx.anytxn.customer.service.IDealCustGatewayService;
import com.jrx.anytxn.feign.gateway.bean.*;
import com.jrx.anytxn.feign.gateway.request.EcifRequest01;
import com.jrx.anytxn.feign.gateway.request.EcifRequest02;
import com.jrx.anytxn.feign.gateway.response.EcifResponse02;
import com.jrx.anytxn.param.entity.PrCodeTable;
import com.jrx.anytxn.param.service.system.ICodeTableService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @program: anytxn-cf-customer
 * @description: 处理客户网关接口服务类
 * @author: xiaoyu.jing
 * @date: 2019-11-26 19:22
 **/
@Service
public class DealCustGatewayServiceImpl implements IDealCustGatewayService {

    @Autowired
    private ICodeTableService codeTableService;

    private static final Logger logger = LoggerFactory.getLogger(DealCustGatewayServiceImpl.class);

    /**
     * 构建Ecif注册请求
     * @param customerInfoCreationBean
     * @param ecifCustId
     * @return
     * @throws SocketException
     * @throws Exception
     */
    @Override
    public String buildRegistEcifReq(CustomerInfoCreationBean customerInfoCreationBean, String ecifCustId, EcifResponse02 ecifRes02) throws SocketException, Exception {
        EcifRequest01 ecifReq = new EcifRequest01();
        ecifReq.setOperation(CustomerConstant.GATEWAY_REGIST_TYPE_01);
        if(StringUtils.isNotBlank(ecifCustId)) {
            ecifReq.setEcifNo(ecifCustId);
            ecifReq.setOperation(CustomerConstant.GATEWAY_REGIST_TYPE_02);
        }

        //客户基本信息
        CustomerInfo ci = this.buildCustInfo(customerInfoCreationBean.getEcifCmCustomerFirstLevel(),customerInfoCreationBean.getEcifCmCustomerSecondLevel(),customerInfoCreationBean.getCustomerSupplyReq());

        //扩展字段原样送回
        if (StringUtils.isNotBlank(ecifCustId) && Objects.nonNull(ecifRes02.getCustInfo())) {
            ci.setSourceExt(ecifRes02.getCustInfo().getSourceExt());
        }

        ecifReq.setCustInfo(ci);

        //xib特殊业务逻辑：若ecif查询结果存在以下字段信息，则对这些字段不更新，保持原来的值
        if (ecifRes02.getCustInfo() != null) {
            CustomerInfo ecifResCi = ecifRes02.getCustInfo();
            ci.setBankMgrNo(ecifResCi.getBankMgrNo());
            ci.setBankOrgNo(ecifResCi.getBankOrgNo());
            ci.setCustomerType(ecifResCi.getCustomerType());
        }

        //公司信息
        CompanyInfo companyInfo = this.buildCompanyInfo(customerInfoCreationBean.getEcifCmCustomerSecondLevel());
        ecifReq.setCompanyInfo(companyInfo);

        //证件信息
        List<DocumentInfo> prtDocumentArray = this.buildDocumentInfo(customerInfoCreationBean.getEcifCmCustomerFirstLevel());
        ecifReq.setPrtDocumentArray(prtDocumentArray);

        if(CollectionUtils.isNotEmpty(customerInfoCreationBean.getAddCmCustomerAddressList())) {
            List<AddressInfo> addressArray = this.buildAddressInfo(customerInfoCreationBean.getAddCmCustomerAddressList());
            ecifReq.setAddressInfosArray(addressArray);
        }

        if(CollectionUtils.isNotEmpty(customerInfoCreationBean.getAddCmCustomerContactList())){
            List<ContractInfo> contractsArray = this.buildContractInfo(customerInfoCreationBean.getAddCmCustomerContactList());
            ecifReq.setContractsArray(contractsArray);
        }

        ecifReq.setServiceId(CustomerConstant.GATEWAY_SERVICE_ID);
        ecifReq.setServiceIp(InternetUtils.getLocalIp());
        ecifReq.setTenantId(customerInfoCreationBean.getTenantId());
        ecifReq.setServiceSeq(SeqUtils.getSN());
        return JsonUtils.toJSon(ecifReq);
    }

    /**
     * 构建查询Ecif请求
     * @param customerInfoCreationBean
     * @return
     * @throws Exception
     */
    @Override
    public String buildQueryEcifReq(CustomerInfoCreationBean customerInfoCreationBean) throws Exception {
        EcifRequest02 ecifRequest02 = new EcifRequest02();
        ecifRequest02.setServiceId(CustomerConstant.GATEWAY_SERVICE_ID);
        ecifRequest02.setServiceIp(InternetUtils.getLocalIp());
        ecifRequest02.setTenantId(customerInfoCreationBean.getTenantId());
        ecifRequest02.setServiceSeq(SeqUtils.getSN());
        ecifRequest02.setQueryType(CustomerConstant.GATEWAY_QUERY_TYPE_01);
        ecifRequest02.setCertNo(customerInfoCreationBean.getEcifCmCustomerFirstLevel().getIdNumber());
        ecifRequest02.setCertType(customerInfoCreationBean.getEcifCmCustomerFirstLevel().getIdType());
        ecifRequest02.setName(customerInfoCreationBean.getEcifCmCustomerFirstLevel().getChineseName());
        return JsonUtils.toJSon(ecifRequest02);
    }

    @Override
    public String buildQueryEcifReq(CustomerInfoBean customerInfoBean) throws Exception {
        EcifRequest02 ecifRequest02 = new EcifRequest02();
        ecifRequest02.setServiceId(CustomerConstant.GATEWAY_SERVICE_ID);
        ecifRequest02.setServiceIp(InternetUtils.getLocalIp());
        ecifRequest02.setTenantId(customerInfoBean.getModifyCmCustomerFirstLevel().getTenantId());
        ecifRequest02.setServiceSeq(SeqUtils.getSN());
        ecifRequest02.setQueryType(CustomerConstant.GATEWAY_QUERY_TYPE_01);
        ecifRequest02.setCertNo(customerInfoBean.getModifyCmCustomerFirstLevel().getIdNumber());
        ecifRequest02.setCertType(customerInfoBean.getModifyCmCustomerFirstLevel().getIdType());
        ecifRequest02.setName(customerInfoBean.getModifyCmCustomerFirstLevel().getChineseName());
        return JsonUtils.toJSon(ecifRequest02);
    }


    /**
     * 构建客户基本信息
     * @param firstLevel
     * @param secondLevel
     * @return
     */
    private CustomerInfo buildCustInfo(CmCustomerFirstLevel firstLevel, CmCustomerSecondLevel secondLevel, CustomerSupplyReq req){
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setMobileNo(secondLevel.getMobile());
        customerInfo.setSex(firstLevel.getSex());
        customerInfo.setBirthDay(DateUtils.format(firstLevel.getBirthDate()));
        customerInfo.setChName(firstLevel.getChineseName());
        customerInfo.setEnName(firstLevel.getEnglishName());
        customerInfo.setRace(firstLevel.getRace());
        customerInfo.setEducationCode(secondLevel.getEducation());
        customerInfo.setMaritalStatus(secondLevel.getMaritalStatus());
        customerInfo.setCompanyPosition(secondLevel.getOccuptionType());

        customerInfo.setOccupation(req.getOccuptionPrimaryType());//esb接口中, 此项表明职业大类
        customerInfo.setOccupationCategory(req.getOccuptionType());//esb接口中, 此项表明职业小类
        customerInfo.setAcctManager(req.getManagerCode());//客户经理编号
        customerInfo.setBankMgrNo(req.getManagerCode());//客户经理编号
        customerInfo.setBankOrgNo(req.getBankOrgNo());//开户分支行编号
        customerInfo.setDisLegalId(req.getDisLegalId());//签发机关编号

        return customerInfo;
    }

    /**
     * 构建客户公司基本信息
     * @param secondLevel
     * @return
     */
    private CompanyInfo buildCompanyInfo(CmCustomerSecondLevel secondLevel){
        CompanyInfo companyInfo = new CompanyInfo();
        companyInfo.setCompanyName(secondLevel.getCompanyName());
        companyInfo.setCompanyType(secondLevel.getCustomerType());
        return companyInfo;
    }

    /**
     * 构建客户证件基本信息
     * @param firstLevel
     * @return
     */
    private List<DocumentInfo> buildDocumentInfo(CmCustomerFirstLevel firstLevel){
        DocumentInfo documentInfo = new DocumentInfo();
        documentInfo.setCertNo(firstLevel.getIdNumber());
        documentInfo.setExpiryDate(firstLevel.getIdExpireDate());
        documentInfo.setGoveIdenNumTypeCode(firstLevel.getIdType());
        documentInfo.setIssAuthority(firstLevel.getIdIssueAgent());
        documentInfo.setEffectDate(firstLevel.getIdEffectiveDate());
        return Collections.singletonList(documentInfo);

    }

    /**
     * 构建客户地址基本信息
     * @param customerAddressInfoList
     * @return
     */
    private List<AddressInfo> buildAddressInfo(List<CmCustomerAddressInfo> customerAddressInfoList) throws TxnBizException {
        List<AddressInfo> addressInfoList = new ArrayList<>();
        for (CmCustomerAddressInfo cmCustomerAddressInfo : customerAddressInfoList) {
            AddressInfo addressInfo = new AddressInfo();
            addressInfo.setAddrType(cmCustomerAddressInfo.getAddressType());
            addressInfo.setDistractNumber(cmCustomerAddressInfo.getDistrict());
            addressInfo.setIssCity(cmCustomerAddressInfo.getCity());
            addressInfo.setIssState(cmCustomerAddressInfo.getProvince());

            //省
            PrCodeTable province = codeTableService.findByTypeAndCodeId(CustomerConstant.CODE_PROVINCE_TYPE,
                    cmCustomerAddressInfo.getProvince(), cmCustomerAddressInfo.getTenantId());

            //核心客编注册所需的省
            Optional<PrCodeTable> ecifProvince = codeTableService.findListByCodeIds(CustomerConstant.CODE_ECIF_PROVINCE_TYPE,
                            cmCustomerAddressInfo.getTenantId())
                    .stream().filter(x -> x.getCodeName().equals(province.getCodeName()))
                    .findFirst();
            if (!ecifProvince.isPresent()) {
                logger.error("核心客编注册时检索省信息不存在，取前端填入的六位码值省：{}，用户：{}", cmCustomerAddressInfo.getProvince(),
                        cmCustomerAddressInfo.getCustomerId());
            } else {
                addressInfo.setIssState(ecifProvince.get().getCodeId());
            }

            //市
            PrCodeTable city = codeTableService.findByTypeAndCodeId(CustomerConstant.CODE_CITY_TYPE,
                    cmCustomerAddressInfo.getCity(), cmCustomerAddressInfo.getTenantId());

            String provinceName = "";
            if (null != province) {
                provinceName = province.getCodeName();
            }
            String cityName = "";
            if (null != city) {
                cityName = city.getCodeName();
            }

            addressInfo.setAddrStreet((provinceName + cityName + cmCustomerAddressInfo.getAddress()).trim());
            addressInfo.setPostCode(cmCustomerAddressInfo.getZipcode());
            addressInfoList.add(addressInfo);
        }
        return addressInfoList;
    }

    /**
     * 构建客户联系人基本信息
     * @param cmCustomerContactInfos
     * @return
     */
    private List<ContractInfo> buildContractInfo(List<CmCustomerContactInfo> cmCustomerContactInfos){
        List<ContractInfo> contractInfoList = new ArrayList<>();
        for(CmCustomerContactInfo cmCustomerContactInfo : cmCustomerContactInfos) {
            ContractInfo contractInfo = new ContractInfo();
            contractInfo.setContractCompayAddr(cmCustomerContactInfo.getCompanyAddress());
            contractInfo.setContractIdenNo(cmCustomerContactInfo.getIdNumber());
            contractInfo.setContractIdenType(cmCustomerContactInfo.getIdType());
            contractInfo.setContractMobile(cmCustomerContactInfo.getMobile());
            contractInfo.setContractName(cmCustomerContactInfo.getChineseName());
            contractInfo.setContractPhone(cmCustomerContactInfo.getHomePhone());
            contractInfo.setContractPosition(cmCustomerContactInfo.getOccuption());
            contractInfo.setContractPostAddr(cmCustomerContactInfo.getHomeAddress());
            contractInfo.setContractType(cmCustomerContactInfo.getRelationship());
            contractInfoList.add(contractInfo);
        }
        return contractInfoList;
    }


}
